package com.xiaomaoguai.fcp.pre.kepler.convert.core;

import com.dh.convert.mapping.BeanMapping;
import com.google.common.collect.Maps;
import com.xiaomaoguai.fcp.pre.kepler.convert.core.support.ConvertZkNode;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.ClassUtils;

import java.util.Map;
import java.util.Objects;

/**
 * @author huwenxuan
 * @date 2018/12/27
 */
@Slf4j
public class ConvertManager {

	private static ClassLoader classLoader = ConvertManager.class.getClassLoader();

	private static final  Map<String, BeanMapping> BEAN_MAPPING_MAP = Maps.newConcurrentMap();

	private static final  Map<String, ConvertZkNode> CONVERT_NODE_MAP = Maps.newConcurrentMap();

	public void add(String beanMappingName, ConvertZkNode convertZkNode) throws ClassNotFoundException {
		BeanMapping beanMapping = initBeanMapping(convertZkNode);
		if (StringUtils.isNotBlank(beanMappingName)) {
			BEAN_MAPPING_MAP.put(beanMappingName, beanMapping);
			CONVERT_NODE_MAP.put(beanMappingName, convertZkNode);
		}
	}

	public void remove(String beanMappingName) {
		if (Objects.nonNull(beanMappingName)) {
			BEAN_MAPPING_MAP.remove(beanMappingName);
			CONVERT_NODE_MAP.remove(beanMappingName);
		}
	}

	public static boolean contains(String beanMappingName) {
		return StringUtils.isNotBlank(beanMappingName) && Objects.nonNull(BEAN_MAPPING_MAP.get(beanMappingName));
	}

	public static int size() {
		return BEAN_MAPPING_MAP.size();
	}

	public static BeanMapping getBeanMapping(String beanMappingName) {
		return StringUtils.isNotBlank(beanMappingName) ? BEAN_MAPPING_MAP.get(beanMappingName) : null;
	}

	public static Map<String, ConvertZkNode> getConvertZkNodeMap() {
		return CONVERT_NODE_MAP;
	}

	/**
	 * 初始化beanMapping
	 *
	 * @param convertZkNode
	 * @return
	 */
	private BeanMapping initBeanMapping(ConvertZkNode convertZkNode) throws ClassNotFoundException {
		BeanMapping beanMapping = new BeanMapping();
		String targetObject = convertZkNode.getTargetObject();
		if (ClassUtils.isPresent(targetObject, classLoader)) {
			beanMapping.init(ClassUtils.forName(targetObject, classLoader), convertZkNode.getBeanMapping());
		} else {
			log.info("ClassNotFoundException , class: {}", targetObject);
		}
		return beanMapping;
	}


}
